package com.twu.biblioteca;

class LoginController extends AbstractController {

    private String username;

    private UserRepository userRepository;

    private Controller next;

    private SecurityContext securityContext;

    void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    void setNext(Controller next) {
        this.next = next;
    }

    void setSecurityContext(SecurityContext securityContext) {
        this.securityContext = securityContext;
    }

    @Override
    public void enter() {
        getUserInterface().prompt("username:");
    }

    @Override
    public Controller handle(String input) {
        if (username == null) {
            username = input;
            getUserInterface().prompt("password:");
            return this;
        } else {
            login(username, input);
            username = null;
            return next;
        }
    }

    boolean login(String username, String password) {
        securityContext.setUser(null);
        User user = userRepository.findByUsername(username);
        if (user != null) {
            boolean passwordIsValid = user.hasPassword(password);
            if (passwordIsValid) {
                securityContext.setUser(user);
                return true;
            }
        }
        return false;
    }

}
